package com.zf.yichat.controller.verification;

import com.zf.yichat.config.utils.GoogleAuthenticationToolUtils;
import com.zf.yichat.config.utils.RedisUtil;
import com.zf.yichat.controller.BaseController;
import com.zf.yichat.model.SysUser;
import com.zf.yichat.utils.common.FsConst;
import com.zf.yichat.utils.response.FsResponse;
import com.zf.yichat.utils.response.FsResponseGen;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Set;

/**
 * 谷歌验证码
 */
@Controller
@RequestMapping("verify")
public class VerifyGoogleCodeController extends BaseController {

    // 谷歌验证器的key值
    public static final String RANDOM_SECRET_KEY = "RANDOM_SECRET";

    // 密钥展示的次数 控制谷歌验证码展示的次数  如果已经展示了就不再展示
    public static final String RANDOM_SECRET_KEY_SHOW_NUM = "RANDOM_SECRET_SHOW_NUM";

    @Autowired
    private RedisUtil redisUtil;

    @RequestMapping("verifyGoogleCode")
    public String index() {
        return "verify/verifyGoogleCode";
    }

    /**
     * 绑定谷歌验证码人员列表
     * @return
     */
    @RequestMapping("googleCodeList")
    public String list() {
        return "verify/googleCodeList";
    }

    /**
     * 前往谷歌两步验证绑定页面
     * @return
     */
    @RequestMapping("/verifyGoogleQRCode")
    @ResponseBody
    public FsResponse toBindingGoogleTwoFactorValidate() throws Exception{

        String username = super.getUser().getUsername();

        // 将生成的key放在redis里
        String randomSecretKey = (String) redisUtil.get(VerifyGoogleCodeController.RANDOM_SECRET_KEY + "_" + username);
        // 控制谷歌验证码展示的次数  如果已经展示了就不再展示
        if (StringUtils.isNotBlank(randomSecretKey)) {
            return FsResponseGen.failMsg("本次验证码已失效，如需要请重置！");
        }

        if (StringUtils.isBlank(randomSecretKey)){
            randomSecretKey = GoogleAuthenticationToolUtils.generateSecretKey();

            redisUtil.set(VerifyGoogleCodeController.RANDOM_SECRET_KEY + "_" + username, randomSecretKey, 0);
        }

        //此步设置的参数就是App扫码后展示出来的参数
        String qrCodeString = GoogleAuthenticationToolUtils.spawnScanQRString(username, randomSecretKey, "");
         String qrCodeImageBase64 = GoogleAuthenticationToolUtils.createQRCode(qrCodeString,null,512,512);
        return FsResponseGen.successData(qrCodeImageBase64);
    }

    /**
     * 校验谷歌验证码
     * @return
     */
    @RequestMapping("/checkGoogleQRCode")
    @ResponseBody
    public FsResponse checkGoogleQRCode(String code){

        String username = getUser().getUsername();

        String key = (String) redisUtil.get(VerifyGoogleCodeController.RANDOM_SECRET_KEY + "_" + username);
        if (StringUtils.isBlank(key)) {
            return FsResponseGen.successMsg(username + "还没有绑定谷歌验证码！");
        }

        long time = System.currentTimeMillis ();
        GoogleAuthenticationToolUtils g = new GoogleAuthenticationToolUtils ();
        boolean result = g.check_code (key, Long.valueOf(code), time);
        if (!result) {
            return FsResponseGen.fail(FsConst.ResponseCode.TWO_FACTOR_CODE_FAIL, "Google身份验证码不正确");
        }

        return FsResponseGen.successMsg("验证通过！");
    }

    /**
     * 重置谷歌验证码
     * @return
     */
    @RequestMapping("/resetGoogleQRCode")
    @ResponseBody
    public FsResponse resetGoogleQRCode(String userName) throws Exception{

        // 删除原有KEY值
        redisUtil.del(VerifyGoogleCodeController.RANDOM_SECRET_KEY + "_" + userName);

//        // 生成新的KEY值
//        String key = GoogleAuthenticationToolUtils.generateSecretKey();
//        redisUtil.set(VerifyGoogleCodeController.RANDOM_SECRET_KEY + "_" + userName, key, 0);
//
//        // 创建绑定的用户名
//        String username = super.getUser().getUsername();
//        String qrCodeString = GoogleAuthenticationToolUtils.spawnScanQRString(username, key, "");
//        String qrCodeImageBase64 = GoogleAuthenticationToolUtils.createQRCode(qrCodeString,null,512,512);
        return FsResponseGen.successMsg("重置成功！");
    }

    /**
     * 重置所有用户的谷歌验证码
     * @return
     */
    @RequestMapping("/resetAllGoogleQRCode")
    @ResponseBody
    public FsResponse resetAllGoogleQRCode() throws Exception{
        Set<String> keys = redisUtil.likeKeys(VerifyGoogleCodeController.RANDOM_SECRET_KEY);
        for (String key : keys) {
            // 删除原有KEY值
            redisUtil.del(key);
        }
        return FsResponseGen.successMsg("重置成功！");
    }

    /**
     * 查询所有绑定谷歌验证码的用户
     * @return
     */
    @RequestMapping("/queryGoogleQRCode")
    @ResponseBody
    public FsResponse queryGoogleQRCode() throws Exception{
        String username = super.getUser().getUsername();
        // 判断是否是admin用户，只有admin用户可以重置
        if (!"admin".equals(username)){
            return FsResponseGen.failMsg("该功能只有admin有权限操作！");
        }

        ArrayList<SysUser> list = new ArrayList<>();
        Set<String> keys = redisUtil.likeKeys(VerifyGoogleCodeController.RANDOM_SECRET_KEY);
        for (String key : keys) {
            int index = key.lastIndexOf("_");
            if (index >= 0 && index < key.length() - 1) {
                String name = key.substring(index + 1);
                if (StringUtils.isNotBlank(name)) {
                    SysUser sysUser = new SysUser();
                    sysUser.setUsername(name);
                    list.add(sysUser);
                }
            }

        }
        return FsResponseGen.successData(list);
    }
}
